﻿using System.IO;
using System.Text.RegularExpressions;
using GP.Logic;
using GP.Logic.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.EntityClient;
using System.Data.EntityModel;
using System.Data.Entity.Infrastructure;
using System.Data.Entity;

namespace WebForms.Doctor
{
    public partial class CitizenView : System.Web.UI.Page
    {
        private readonly CitizenService _citizenService = new CitizenService();

        protected void Page_Load(object sender, EventArgs e)
        {

            var gp = new GpContext();
            GpSysUser gpSysUser = gp.GpSysUsers.Single(a => a.Username == User.Identity.Name);
            gp.Citizens.Where(a => a.DocId == gpSysUser.DocId).OrderBy(a => a.Name).Load();
            //Tjekkes op imod om der er et aktuelt event på nogle patienter
            //gvCitizens.DataSource = gp.Citizens.Local;
            //gvCitizens.DataBind();

            DoctorService doctorService = new DoctorService();
            

            DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath("~/xml"));

            ICollection<Citizen> list = new List<Citizen>();
            foreach (var info in directoryInfo.GetDirectories())
            {
                if (!Regex.IsMatch(info.Name, "^[0-9]{1,}$"))
                    continue;

                long citizenId = long.Parse(info.Name);

                bool hasAccessTo = doctorService.HasAccessTo(citizenId);

                if(!hasAccessTo)
                    continue;

                var citizen = _citizenService.GetCitizen(citizenId);
                list.Add(citizen);
            }

            dlCitizens.DataSource = list;
            dlCitizens.DataBind();
        }

        protected ICollection<Data> GetList(string citizenIdString)
        {
            var list = new List<Data>();

            string combine = Path.Combine(Server.MapPath("~/xml"), citizenIdString);

            var info = new DirectoryInfo(combine);

            long citizenId = long.Parse(citizenIdString);

            foreach (var fileInfo in info.GetFiles())
            {
                var data = new Data(citizenId, fileInfo.Name);
                list.Add(data);
            }

            return list;
        }
    }

    public class Data
    {
        public string Path { get; set; }
        public string Name { get; set; }
        public long CitizenId { get; set; }
        public string Url
        {
            get { return "~/xml/" + CitizenId + "/" + Name; }
        }

        public Data(long citizenId, string name)
        {
            CitizenId = citizenId;
            Name = name;
        }
    }
}